package site.teamo.biu.flink.web.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import site.teamo.biu.flink.web.controller.model.BiuJSONResult;
import site.teamo.biu.flink.web.exception.BiuRuntimeException;
import site.teamo.biu.flink.web.exception.BiuValidationException;
import site.teamo.biu.flink.web.util.BiuJSONResultUtils;

import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BiuValidationException.class)
    public BiuJSONResult handleException(BiuValidationException e) {
        return BiuJSONResultUtils.error(
                e.getCode(),
                String.join(",", e.getValidationResult().values()));
    }

    @ExceptionHandler(BiuRuntimeException.class)
    public BiuJSONResult handleException(BiuRuntimeException e) {
        log.error("运行时异常", e);
        return BiuJSONResultUtils.error(
                e.getCode(),
                e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BiuJSONResult handleException(Exception e) {
        log.error("发生未知错误", e);
        return BiuJSONResultUtils.error(-1, "未知错误");
    }

}
